<?php

declare(strict_types=1);

namespace Zyucv7\Components\DataAccess\Services;

use Zyucv7\Components\DataAccess\Uxts\Expert\Task as ExpTaskModel;
use Zyucv7\Components\DataAccess\Uxts\Expert\Option as ExpOptionModel;
use Zyucv7\Core\View\View;

/**
 * 专家任务表
 */
class ExpTask
{

    private $view;

    public function __construct()
    {
        $this->view = new View(__DIR__.'/tmpls');
    }

    // 获取任务分类
    public function getExpTaskCategory()
    {
        $model = new ExpOptionModel();
        $rows = $model->getParents();
        return $rows;
    }

    // 获取专家任务情况，返回文本
    public function getExpTaskInfo($params)
    {
        $options = $this->getExpTaskCategory();
        $model = new ExpTaskModel();
        $query = $model->allRelationQuery();
        if (isset($params['time_range'])) {
            $time_range = $params['time_range'];
            $query->whereBySql('exp_task.assign_time BETWEEN ? AND ?', [$time_range[0], $time_range[1]]);
            $this->view->with('start_date', $time_range[0]);
            $this->view->with('end_date', $time_range[1]);
        }
        $query->order('exp_task.assign_time', 'DESC');
        // $query->limit(5);
        $rows = $query->getAll();
        // print_r($rows);
        $finish = 0;
        $progress = 0;
        foreach ($rows as $row) {
            // 0-未接受,1-已退回,2-已指派,3-已处理,4-已评价,5-跟进中,6-申请延期,7-审核中,8-审核通过,9-审核不通过',
            $status = intval($row['task_status']);
            if ($status == 3 || $status == 4 || $status == 8) {
                $finish++;
            } else {
                $progress++;
            }
        }

        foreach ($options as &$option) {
            $option['count'] = 0;
            $childId = $option['childId'] ?? [];
            foreach ($rows as $row) {
                if (in_array($row['task_option'], $childId)) {
                    $option['count']++;
                }
            }
        }
        $newOptions = [];
        foreach ($options as $option) {
            if ($option['count'] > 0) {
                $newOptions[] = [
                    'name' => $option['name'],
                    'count' => $option['count'],
                ];
            }
        }
        // foreach($newOptions as $opitem):
        //     echo $opitem['name'].'_'.$opitem['count'];
        // endforeach;
        $this->view->with('total_tasks', count($rows));
        $this->view->with('completed_tasks', $finish);
        $this->view->with('pending_tasks', $progress);
        $this->view->with('newOptions', $newOptions);
        return $this->view->render('jianbao');
        
    }
}
